package com.agileboot.attendance.domain.acceptance.model;

import cn.hutool.core.bean.BeanUtil;
import com.agileboot.attendance.domain.acceptance.dto.AcceptanceRequest;
import com.agileboot.attendance.domain.acceptance.entity.AttAcceptanceEntity;
import com.agileboot.attendance.domain.acceptance.db.service.AttAcceptanceService;
import com.agileboot.common.exception.ApiException;
import com.agileboot.common.exception.error.ErrorCode;
import com.agileboot.infrastructure.user.AuthenticationUtils;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;
import java.util.Date;
import java.math.BigDecimal;

/**
 * 验收单领域模型
 */
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class AcceptanceModel extends AttAcceptanceEntity {

    private transient AttAcceptanceService acceptanceService;

    public AcceptanceModel(AttAcceptanceEntity entity) {
        if (entity != null) {
            BeanUtil.copyProperties(entity, this);
        }
    }

    public AcceptanceModel(AttAcceptanceEntity entity, AttAcceptanceService acceptanceService) {
        this(entity);
        this.acceptanceService = acceptanceService;
    }

    /**
     * 从请求对象加载数据
     */
    public void loadFromRequest(AcceptanceRequest request) {
        if (request != null) {
            BeanUtil.copyProperties(request, this);
        }
        
        // 设置初始状态
        if (this.getStatus() == null) {
            this.setStatus(0); // 待验收状态
        }
    }

    /**
     * 校验字段
     */
    public void checkFields() {
        if (this.getAmount() == null || this.getAmount().compareTo(BigDecimal.ZERO) <= 0) {
            throw new ApiException(ErrorCode.Client.COMMON_REQUEST_PARAMETERS_INVALID, "验收金额必须大于0");
        }
        if (this.getAcceptanceTime() == null || this.getAcceptanceTime().isAfter(LocalDateTime.now())) {
            throw new ApiException(ErrorCode.Client.COMMON_REQUEST_PARAMETERS_INVALID, "验收时间不能为空或晚于当前时间");
        }
    }

    /**
     * 创建验收单
     */
    public void insertAcceptance() {
        this.setCreatorId(AuthenticationUtils.getUserId());
        this.setDeleted(false);
        if (!acceptanceService.save(this)) {
            throw new ApiException(ErrorCode.Internal.DB_INTERNAL_ERROR);
        }
    }

    /**
     * 更新验收单
     */
    public void updateAcceptance() {
        this.setUpdaterId(AuthenticationUtils.getUserId());
        if (!acceptanceService.updateById(this)) {
            throw new ApiException(ErrorCode.Internal.DB_INTERNAL_ERROR);
        }
    }

    /**
     * 删除验收单
     */
    public void deleteAcceptance() {
        this.setDeleted(true);
        this.setUpdaterId(AuthenticationUtils.getUserId());
        if (!acceptanceService.updateById(this)) {
            throw new ApiException(ErrorCode.Internal.DB_INTERNAL_ERROR);
        }
    }
} 